package cn.ulc.socket.weapp.controller;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import cn.ulc.common.annotation.IgnoreAuth;
import cn.ulc.common.model.param.PaginationParam;
import cn.ulc.common.util.HttpUtil;
import cn.ulc.common.util.Result;
import cn.ulc.socket.weapp.model.dto.OrderPayDTO;
import cn.ulc.socket.weapp.model.param.OrderParam;
import cn.ulc.socket.weapp.model.param.OrderSaveParam;
import cn.ulc.socket.weapp.service.OrderServ;
import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.bean.result.BaseWxPayResult;
import com.github.binarywang.wxpay.service.WxPayService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;

@Controller
@RequestMapping(value = "/wechat/order")
public class OrderController {
    private static final Log log = LogFactory.get();

    @Autowired
    OrderServ ordersServ;
    @Autowired
    WxPayService wxPayService;

    @PostMapping("/createOrder")
    @ResponseBody
    public Result createOrder(@Validated @RequestBody OrderSaveParam param , BindingResult result){
        if(result.hasErrors()) {
            log.error("登录错误",result.getFieldError().getDefaultMessage());
            return Result.fail(result.getFieldError().getDefaultMessage());
        }
        return Result.success(ordersServ.createOrder(param));
    }
    /**
     * 订单支付
     */
    @PostMapping("/orderToPay")
    @ResponseBody
    public Result orderToPay(HttpServletRequest request, @Validated @RequestBody OrderParam param, BindingResult result) {
        if(result.hasErrors()) {
            log.error("订单支付",result.getFieldError().getDefaultMessage());
            return Result.fail(result.getFieldError().getDefaultMessage());
        }
        //获取当前登录用户IP地址
        String ipAddress = HttpUtil.getIpAddress(request);
        log.info("orderToPay==HttpUtil==getIpAddress() :" + ipAddress);
        OrderPayDTO dto = ordersServ.orderToPay(ipAddress , param);
        return Result.success(dto);
    }
    /**
     * 订单支付回调
     */
    @IgnoreAuth
    @PostMapping("/payCallBack")
    public void payCallBack(HttpServletRequest request,HttpServletResponse response) {
        log.info("PayCallBack ");
        String xmlResult = "";
        String resXml = "";
        try {
            xmlResult =IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
            String result = ordersServ.payCallBack(xmlResult);
            if(!"success".equals(result)){
                WxPayNotifyResponse.success("code:" + 9999 + "微信回调结果异常,异常原因:"+result );
            }
            WxPayOrderNotifyResult notifyResult = wxPayService.parseOrderNotifyResult(xmlResult);
            // 结果正确 outTradeNo
            String orderNo = notifyResult.getOutTradeNo();
            log.info("orderNo==="+orderNo);
            String tradeNo = notifyResult.getTransactionId();
            log.info("tradeNo==="+tradeNo);
            String totalFee = BaseWxPayResult.fenToYuan(notifyResult.getTotalFee());
            log.info("微信支付回调付款总金额==>{}元", totalFee);
            // 自己处理订单的业务逻辑，需要判断订单是否已经支付过，否则可能会重复调用
            // 通知微信.异步确认成功.必写.不然会一直通知后台.十次之后就认为交易失败了.
            resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
                    + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
            response.setContentType("text/xml");
            BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
            out.write(resXml.getBytes());
            out.flush();
            out.close();
//            return WxPayNotifyResponse.success("成功");
            log.info("xmlResult===="+xmlResult);
        }catch (Exception e){
            e.printStackTrace();
             WxPayNotifyResponse.success("code:" + 9999 + "微信回调结果异常,异常原因:" + e.getMessage());
        }
//        return ordersServ.payCallBack(xmlResult);
    }

    @GetMapping("/")
    @ResponseBody
    public Result findListPage(String status,PaginationParam param){
        return Result.success(ordersServ.findListPage(status,param));
    }
    @GetMapping("/findDetail")
    @ResponseBody
    public Result orderDetail(String orderNo) {
        return Result.success(ordersServ.findDetail(orderNo));
    }

    @PutMapping("/cancelOrder/{id}")
    @ResponseBody
    public Result cancelOrder(@PathVariable("id") Long id){
        return Result.success(ordersServ.cancelOrder(id));
    }
}
